<template>
  <div class="black-red-list">
    <div class="search">
      <div class='fl'>
        <span class="icon-text" @click.stop="addBlackRedList"><i class="el-icon-plus"></i>添加</span>
        <span class="icon-text" @click.stop="refresh"><i class="iconfont icon-shuaxin"></i>刷新</span>
        <span class="icon-text" :class="disabledReload?'disabled-text':''" @click.stop="active"><i class="icon iconfont icon-fasongchenggong" :class="disabledReload?'disabled-icon':''"></i>生效</span>
        <span class="icon-text" @click.stop="batchExport" style="margin-right: 2px;"><i class="icon-daochu1 iconfont"></i>批量导出</span>
        <questionToolTip tipContent="每次导出上限为10000条" style="margin-right: 18px;"></questionToolTip>
        <span class="icon-text" @click.stop="batchDel"><i class="icon-shanchu iconfont"></i>批量删除</span>
        <el-select size="mini" v-model="blackRedType" :placeholder="$t('public.pleasePick')" class="select" @change="typeChangeSearch">
          <el-option
            v-for="item in BlackType"
            :key="item.value"
            :label="item.name"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <el-input
          placeholder="请输入电话号搜索"
          size="mini"
          class="condition"
          v-model="searchContent"
          @keyup.enter.native="searchByNum">
          <i
            class="el-input__icon el-icon-search"
            slot="suffix"
            @click="searchByNum">
          </i>
        </el-input>
      </div>
      <pagination class="page"
                  :small="true"
                  :currentPage="currentPage"
                  :count="count || 0"
                  :pageSize="pageSize"
                  :totalPage="totalPage"
                  @turnPage="turnPage">
      </pagination>
    </div>
    <div>
      <el-table
        class="table"
        ref="multipleTable"
        @selection-change="handleSelectionChange"
        :data="tableData">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="BlackNum"
          label="电话号码">
        </el-table-column>
        <el-table-column
          prop="TypeName"
          label="名单类型">
        </el-table-column>
        <el-table-column
          prop="Memo"
          label="备注">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.Memo" placement="top">
              <div class="memo_box" style="white-space: nowrap;">{{scope.row.Memo}}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          prop="UpdateTime"
          label="最后修改时间">
        </el-table-column>
        <el-table-column
          width="200"
          label="操作">
          <template slot-scope="scope">
            <el-button type="text" class="update-btn" size="small" @click="update(scope.row)">修改</el-button>
            <el-button type="text" class="delete-btn del" size="small" @click="del(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <left-slide :title="title" :visible.sync="isShowDetail" :showFooter="false">
      <black-list-detail v-show='isShowDetail' :isSimpleConfig="true" :lastAllBlackRedList="lastAllBlackRedList" :currentData="currentData" :showBread="showBread" @resh='refresh' @reload="reload"  @cancle="cancle"></black-list-detail>
    </left-slide>
  </div>
</template>
<script>
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import Pagination from '@/components/public-modules/card/Pagination'
  import questionToolTip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
  import BlackListDetail from '../../../config/channelConfig/telCustomerService/BlackListDetail.vue'
  import {deepClone} from '@/utils/m7Utils.js'
  export default {
    data () {
      return {
        showBread: '',
        title: '',
        tableData: [],
        oldPBX: '',
        blackRedType: '',
        disabledReload: true,   //  生效按钮是否能被点击
        searchContent: '',    //  手机号查询
        currentPage: 1,
        count: 0,
        pageSize: 10,
        isShowDetail: false,
        lastAllBlackRedList: [],
        currentData: {},
        emptyFrom: {_id: '', BlackNum: '', Type: '', Memo: '', PBX: this.$store.state.session.user.pbx, TypeName: ''},
        BlackType: [{value: '', name: '全部'}, {value: '0', name: '红名单'}, {value: '1', name: '呼入黑名单'}, {value: '2', name: '外呼黑名单'}],
        choosedArr: [],   //   被选中  的数组
        choosedIds: []   //   被选中  批量删除 导出的  ids
      }
    },
    methods: {
        //   查询
      search () {
        let data = {}
        data.Account = this.$store.state.session.account.account
        data.PBX = this.PBX
        data.BlackNum = this.searchContent
        data.Type = this.blackRedType
        data.page = this.currentPage
        data.limit = this.pageSize
        this.$store.dispatch('queryBlackNum', data).then(resp => {
          if (resp && resp.success) {
            this.tableData = resp.list
            this.tableData.forEach(item => {
              if (item.Type === '0') {
                item.TypeName = '红名单'
              } else if (item.Type === '1') {
                item.TypeName = '呼入黑名单'
              } else {
                item.TypeName = '外呼黑名单'
              }
            })
            this.count = resp.count
          } else {
            this.$message.error('查询失败！')
          }
        })
      },
//      初始化
      init () {
        this.currentPage = 1
        this.searchContent = ''
        this.blackRedType = ''
        this.search()
      },
//      按手机号搜索
      searchByNum () {
        this.currentPage = 1
        this.search()
      },
//      按类型搜索
      typeChangeSearch () {
        this.currentPage = 1
        this.search()
      },
      turnPage (val) {
        this.currentPage = val
        this.search()
      },
      cancle () {
        this.isShowDetail = false
      },
      addBlackRedList () { // 添加黑红名单
        this.showBread = 'addBlackRedList'
        this.title = this.$t('channelsettings.redBlack10')
        this.currentData = deepClone(this.emptyFrom)
        this.isShowDetail = true
      },
      update (val) { // 编辑黑红名单
        this.showBread = 'editBlackRedList'
        this.title = this.$t('channelsettings.redBlack9')
        this.currentData = deepClone(val)
        this.isShowDetail = true
      },
//      批量导出
      batchExport () {
//       导出选中数据
        if (this.choosedIds.length < this.tableData.length && this.choosedIds.length > 0) {
          let query = {}
          query.account = this.$store.state.session.account.account
          query._ids = this.choosedIds
          query.phone = ''
          query.type = ''
          query.pbx = this.PBX
          this.exportXls(query)
        } else if (this.choosedIds.length === this.tableData.length || this.choosedIds.length === 0) {
//            导出全部
          let query = {}
          query.account = this.$store.state.session.account.account
          query._ids = []
          query.phone = this.searchContent
          query.type = this.blackRedType
          query.pbx = this.PBX
          this.exportXls(query)
        }
      },
      exportXls (query) {
        let data = {
          Method: 'exportBlackRedNum',
          Query: query
        }
        this.$store.dispatch('exportXls', data).then((res) => {
          if (res.success) {
            this.$message({
              type: 'success',
              message: '导出成功!'
            })
          }
        })
      },
//      批量删除
      batchDel () {
        if (this.choosedArr.length < 1) {
          this.$message.error('请选择删除数据')
          return
        }
        this.$confirm('确定批量删除吗？', this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.batchDelAct()
        }).catch(() => {
          console.log('取消')
        })
      },
      batchDelAct () {
        let data = this.choosedArr
        this.$store.dispatch('batchDeleteBlackNumber', data).then(resp => {
          if (resp.success) {
            this.refresh()
            this.getAllBlacklist()
            this.disabledReload = false
            this.$message.success(this.$t('sms.successDel'))
          } else {
            this.disabledReload = false
            // this.$message.error(this.$t('sms.failDel'))
          }
        })
      },
//      单个删除
      del (val) {
        this.$confirm('确定要删除该条信息吗？', this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.deleteBlackList(val)
        }).catch(() => {
          console.log('取消')
        })
      },
      deleteBlackList (val) {
        let data = {}
        if (val) {
          data._id = val._id
        }
        data.Account = this.$store.state.session.account.account
        data.BlackNum = val.BlackNum || ''
        data.PBX = val.PBX || ''
        data.Type = val.Type || ''
        data.Memo = val.Memo || ''
        this.$store.dispatch('delBlackNum', data).then(resp => {
          if (resp.success) {
            this.refresh()
            this.getAllBlacklist()
            this.disabledReload = false
            this.$message.success(this.$t('sms.successDel'))
          } else {
            this.disabledReload = true
            this.$message.error(this.$t('sms.failDel'))
          }
        })
      },
      refresh () {
        this.init()
      },
      reload (flag) { // 生效可以点击
        this.disabledReload = flag
        this.getAllBlacklist()
      },
      active () {
        let obj = {}
        obj.PBX = this.PBX
        obj.Account = this.$store.state.session.account.account
        this.$store.dispatch('reloadIvr', obj).then(res => {
          if (res.success) {
            this.disabledReload = true
            this.$message({
              type: 'success',
              message: this.$t('configLazyLoad.process.effectiveSuccessfully')
            })
          }
        })
      },
//      复选框点击事件
      handleSelectionChange (val) {
        this.choosedArr = val
        let ids = []
        this.choosedArr.forEach(item => {
          ids.push(item._id)
        })
        this.choosedIds = ids
      },
      getAllBlacklist () {
        //   取到所有黑名单     用于黑名单排重
        let data = {}
        data.Account = this.$store.state.session.account.account
        this.$store.dispatch('queryBlackNum', data).then(resp => {
          if (resp && resp.success) {
            this.lastAllBlackRedList = resp.list
          }
        })
      }
    },
    components: {
      questionToolTip,
      BlackListDetail,
      leftSlide,
      Pagination
    },
    watch: {
      PBX () {
        let routerName = this.$route.meta.title
        if (routerName === 'blackRedList') {
          this.init()
        }
      }
    },
    computed: {
      PBX () {
        return this.$store.state.config.callCenter.currentPBX
      },
      totalPage () {
        return Math.ceil(this.count / this.pageSize) || 1
      }
    },
    deactivated () {
      this.oldPBX = this.PBX
    },
    activated () {
      if (this.oldPBX !== this.PBX) {
        this.init()
      }
    },
    beforeMount () {
      this.getAllBlacklist()
//      this.init()
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .black-red-list
    padding 20px
    padding-bottom 50px
  .search
    height 30px
    padding 8px 10px
    border 1px solid #E7E7EB
    border-bottom none
    .el-icon-plus,.icon-shuaxin,.icon-fasongchenggong,.icon-reciguanli,.icon-daochu1,.icon-shanchu
      color $c-main
      font-size 12px
      margin-right 2px
    .disabled-icon
      color #9D9B9D
    .select
      margin-right 20px
    .condition
      width 270px
      margin-right 8px
    .page
      float right
    .icon-text
      margin-right 16px
      cursor pointer
      line-height 30px
    .disabled-text
      cursor not-allowed
  .table
    .update-btn
      cursor pointer
    .delete-btn
      cursor pointer
      color $c-pink
  .batch-wrap
    position fixed
    bottom 0
    width 100%
    height 40px
    align-items center
    background #fff
    color $cf-gray3
    padding-left 10px
    font-size 12px
    margin-top 14px
    box-shadow 1px -2px 7px rgba(0,0,0,0.1)
  .el-table .cell >.el-button--text.del
    color $c-pink
    cursor pointer
  .memo_box 
    white-space nowrap
    display inline-block
    max-width 100%
    text-overflow ellipsis
    overflow hidden
</style>
